import React, { useState, useEffect, useRef } from "react";
import "@/pages/index.less";
import "@/components/Card/index.less";
import "./index.less";
const manPng = require("@/assets/image/bucket_echart/man.png");

import Generator, {
  defaultCommonSettings,
  defaultGlobalSettings,
  defaultSettings,
} from "fr-generator";
import { useDebounce, useDebounceFn } from "ahooks";

import {
  Tabs,
  Select,
  Tooltip,
  Table,
  Tag,
  message,
  Dropdown,
  Menu,
  Input,
  Pagination,
  Row,
  Col,
  Space,
  Button,
  Divider,
  Modal,
  Form,
  Radio,
  TreeSelect,
} from "antd";
const { TabPane } = Tabs;

import * as echarts from "echarts";

import * as Api from "@/servers/api";
import * as Api2 from "@/servers/formFill";

import { GetProjectList } from "@/servers/DataPlan";

import { DatePicker } from "@/components/DatePicker/index";
const { RangePicker } = DatePicker;
import dayjs from "dayjs";

import { history } from "umi";
import { connect } from "dva";
import rule from "@/tool/formrule";

const DataSourceDetailView = (props: any) => {
  const { data1, data5, data6, datas, allProjects } = props;
  const [projectId, setProjectId] = useState(props.location.query.projectId);
  const [projson, setprojson] = useState({});

  const [formInstance] = Form.useForm();
  const [formInstance2] = Form.useForm();

  const projectIdWatch = Form.useWatch("projectId", formInstance2);
  const tableHierarchyWatch = Form.useWatch("tableHierarchy", formInstance2);

  const [tree_and_project, settree_and_project] = useState([]);

  useEffect(() => {
    if (projectIdWatch && tableHierarchyWatch) {
      // 同时有值，去调用后台接口
      Api.GetMenuList(
        {
          projectId: projectIdWatch,
          pid: 0,
        },
        tableHierarchyWatch
      ).then((res) => {
        settree_and_project(res?.data);
        formInstance2.setFieldsValue({
          tableId: undefined, // 重置表id
        });
      });
    }
  }, [projectIdWatch, tableHierarchyWatch]);

  // console.log('defaultCommonSettings--', defaultCommonSettings);
  // console.log('defaultGlobalSettings', defaultGlobalSettings);
  // console.log('defaultSettings', defaultSettings);

  const instance2 = React.useRef();
  const [valueInput, setValueInput] = useState("表单名称");
  const onChangeInput = (e: any) => {
    setValueInput(e.target.value as any);
  };

  useEffect(() => {
    addName_slow();
  }, [valueInput]);

  const [formId, setFormId] = useState("");

  const addName = async () => {
    if (formId) {
      const res = await Api2.formname({
        // 编辑操作
        id: formId,
        name: valueInput,
        description: "",
      });
      if (!res?.type) {
        console.log(res?.data);
        setFormId(res?.data);
      }
    } else {
      if (valueInput == "表单名称") return;
      const res = await Api2.formnameCreate({
        // 新增操作
        name: valueInput,
        description: "",
      });
      if (!res?.type) {
        console.log(res?.data);
        setFormId(res?.data);
      }
    }
  };

  const { run: addName_slow } = useDebounceFn(addName, { wait: 100 });

  const saveSchema = async () => {
    const schema2 = instance2?.current?.getValue();
    console.log(schema2, 555);
    const res = await Api2.formcontent({ content: schema2, id: formId });
    if (!res?.type) {
      message.success("保存成功！");
    }
  };

  // if(dom) {
  //   return (
  //     <div>提示信息</div>
  //   )
  // }

  const onLoadData_global = (nodeData: any) => {
    return new Promise((resolve) => {
      if (nodeData?.children && nodeData?.children?.length !== 0) {
        resolve(null);
        return;
      }
      getTreeAndTable_global(nodeData.key, resolve);
    });
  };

  const configs: any = {
    ODS: {
      apitree: Api.GetDataSourceTree,
      apitable: Api.GetDataSourceDataList,
    },
    DWD: {
      apitree: Api.GetWarehouseTree,
      apitable: Api.GetWarehouseDataList,
    },
    DWS: {
      apitree: Api.GetDataSetTree,
      apitable: Api.GetDataSetDataList,
    },
    ADS: {
      apitree: Api.GetDataIndexFolder,
      apitable: Api.GetDataIndexTableArr,
    },
  };

  //树懒加载
  const getTreeAndTable_global = async (pid: any, resolve: any) => {
    const treeList = await configs[tableHierarchyWatch].apitree({
      pid: pid,
      projectId: projectIdWatch,
    });
    const tableList = await configs[tableHierarchyWatch].apitable({
      categoryId: pid,
      projectId: projectIdWatch,
      pageIndex: 1,
      pageSize: 1000,
    });
    var children = treeList.data.concat(tableList.data.rows);
    const newArr = updateTreeData_global(tree_and_project, pid, children);
    settree_and_project([...newArr]);
    resolve();
  };

  // pid又变回key，和id匹配
  const updateTreeData_global = (list: any, key: any, children: any) =>
    list.map((node: any) => {
      if (node.id === key) {
        // big ke
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData_global(node.children, key, children),
        };
      }
      return node; // 最终返回dom，node
    });

  return (
    <div className="pageView2bgc">
      <div className="PageContent2bgc">
        <Modal
          title="选择数据来源表"
          width={"50%"}
          visible={isModalOpen3}
          onOk={handleOk3}
          onCancel={handleCancel3}
        >
          <div>
            <Form
              // layout="vertical"
              form={formInstance2}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 18 }}
              // style={{ width: "70%", marginTop: 30 }} // 不用包裹div
              onFinish={onFinish}
            >
              <Form.Item
                name="datafrom" // name就是v-model 双向绑定
                label="数据来源"
                rules={[]}
                initialValue={"DATA_CENTER"}
              >
                <Radio.Group>
                  <Radio value={"DATA_CENTER"}>数据中台</Radio>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="projectId" // name就是v-model 双向绑定
                label="选择项目"
                rules={[rule.required]}
              >
                <Select
                  placeholder="请选择"
                  allowClear
                  getPopupContainer={(triggerNode) => triggerNode.parentElement}
                  fieldNames={{ label: "displayName", value: "id" }} // 省的自己去递归
                  options={projectList}
                />
              </Form.Item>
              <Form.Item
                name="tableHierarchy" // name就是v-model 双向绑定
                label="选择数据类型"
                rules={[rule.required]}
              >
                <Radio.Group>
                  <Radio value={"ODS"}>原始库</Radio>
                  <Radio value={"DWD"}>主题库</Radio>
                  <Radio value={"DWS"}>专题库</Radio>
                  <Radio value={"ADS"}>指标库</Radio>
                  {/* 同一个value，会导致同时选中。 */}
                </Radio.Group>
              </Form.Item>
              <Form.Item
                name="tableId"
                label="选择数据表"
                rules={[rule.required]}
              >
                <TreeSelect
                  treeDefaultExpandedKeys={[0]}
                  dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                  placeholder="请选择"
                  loadData={onLoadData_global}
                  treeData={tree_and_project}
                  allowClear
                  fieldNames={{ label: "name", value: "id" }} // 省的自己去递归，交给antd去递归
                />
              </Form.Item>
              <Form.Item label="数据预览" colon={false}>
                <div style={{ color: "#aaa" }}>（最多预览5行数据）</div>
              </Form.Item>
              {/* 分区组件，不需要传递props下去，分区是function组件，复用代码 */}
              {/* <AddFenqu></AddFenqu> */}
              <div>
                {/* 让表格居中，用margin属性即可 */}
                <Table
                  columns={columns2}
                  dataSource={[]}
                  style={{ width: "85%", margin: "0 auto" }}
                />
              </div>
              <Form.Item
                labelCol={{ span: 6 }}
                wrapperCol={{ offset: 10, span: 12 }}
              >
                <Space>
                  <Button type="primary" htmlType="submit">
                    保存
                  </Button>
                  <Button
                    onClick={() => {
                      // goBack();
                    }}
                  >
                    取消
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        </Modal>
      </div>
    </div>
  );
};

const mapStateToProps = (state: any) => {
  const { datas, allProjects } = state.model_dataassets_general;
  const { User } = state.model_user;
  return {
    datas,
    allProjects,
    User,
  };
};
export default connect(mapStateToProps)(DataSourceDetailView);
